package com.sea.finance.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.finance.entity.RefusedTax;
import com.sea.finance.entity.Vt;
import com.sea.finance.entity.VtFeeMatch;
import com.sea.finance.entity.VtFile;
import com.sea.finance.service.VtFeeMatchService;
import com.sea.finance.service.VtFileService;
import com.sea.finance.service.VtService;
import com.sea.supply.entity.Buy;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 运费
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/finance/vtFeeMatch")
public class VtFeeMatchController {
    @Autowired
    private VtFeeMatchService vtFeeMatchService;
    @Autowired
    private VtService vtService;

    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/finance/vtReport/feeMatchMain";
    }
    @RequestMapping("/feeNameMatchMain")
    public String feeMatch(Model model) {
        return "/sea/finance/vtReport/feeNameMatchMain";
    }

    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     VtFeeMatch vtFeeMatch) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<VtFeeMatch> list = vtFeeMatchService.findByCnd(vtFeeMatch);
        PageInfo<VtFeeMatch> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @ResponseBody
    @RequestMapping("/feeMatch")
    public AjaxTableReturn feeMatch(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     VtFeeMatch vtFeeMatch) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<VtFeeMatch> list = vtFeeMatchService.feeMatch(vtFeeMatch);
        PageInfo<VtFeeMatch> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @RequestMapping("/importFeeMatch")
    @ResponseBody
    public AjaxReturn importDetail(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                vtFeeMatchService.importDetail(file.getInputStream(),fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportByFeeName", method = RequestMethod.GET)
    public void exportByFeeName(HttpServletResponse response,String feeName) throws IOException {
        List<Vt> list = vtService.findByFeeName(feeName);
        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("费用类型匹配表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("id"));
        customHead.add(Arrays.asList("period"));
        customHead.add(Arrays.asList("shop_name"));
        customHead.add(Arrays.asList("brand_name"));
        customHead.add(Arrays.asList("country_name"));
        customHead.add(Arrays.asList("file_name"));
        customHead.add(Arrays.asList("settlement_id"));
        customHead.add(Arrays.asList("settlement_start_date"));
        customHead.add(Arrays.asList("settlement_end_date"));
        customHead.add(Arrays.asList("deposit_date"));
        customHead.add(Arrays.asList("total_amount"));
        customHead.add(Arrays.asList("currency"));
        customHead.add(Arrays.asList("transaction_type"));
        customHead.add(Arrays.asList("order_id"));
        customHead.add(Arrays.asList("merchant_order_id"));
        customHead.add(Arrays.asList("adjustment_id"));
        customHead.add(Arrays.asList("shipment_id"));
        customHead.add(Arrays.asList("marketplace_name"));
        customHead.add(Arrays.asList("amount_type"));
        customHead.add(Arrays.asList("amount_description"));
        customHead.add(Arrays.asList("amount"));
        customHead.add(Arrays.asList("fulfillment_id"));
        customHead.add(Arrays.asList("posted_date"));
        customHead.add(Arrays.asList("posted_date_time"));
        customHead.add(Arrays.asList("order_item_code"));
        customHead.add(Arrays.asList("merchant_order_item_id"));
        customHead.add(Arrays.asList("merchant_adjustment_item_id"));
        customHead.add(Arrays.asList("sku"));
        customHead.add(Arrays.asList("quantity_purchased"));
        customHead.add(Arrays.asList("promotion_id"));
        customHead.add(Arrays.asList("fee_name"));
        customHead.add(Arrays.asList("listing_name"));

        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("费用类型匹配表")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToCustomOrder(list)); // 转换数据顺序
    }

    @ResponseBody
    @RequestMapping(value = "/exportAllByFeeName", method = RequestMethod.GET)
    public void exportAllByFeeName(HttpServletResponse response) throws IOException {
        List<Vt> list = new ArrayList<>();
        List<VtFeeMatch> vList = vtFeeMatchService.feeMatch(null);
        if(null != vList && vList.size()!=0){
            for(VtFeeMatch vtFeeMatch:vList){
                if(StringUtils.isBlank(vtFeeMatch.getFeeType())){
                    List<Vt> vtList = vtService.findByFeeName(vtFeeMatch.getFeeName());
                    if(null!=vtList && vtList.size()!=0){
                        for(Vt vt:vtList){
                            list.add(vt);
                        }
                    }
                }

            }
        }
        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("费用类型匹配表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("id"));
        customHead.add(Arrays.asList("period"));
        customHead.add(Arrays.asList("shop_name"));
        customHead.add(Arrays.asList("brand_name"));
        customHead.add(Arrays.asList("country_name"));
        customHead.add(Arrays.asList("file_name"));
        customHead.add(Arrays.asList("settlement_id"));
        customHead.add(Arrays.asList("settlement_start_date"));
        customHead.add(Arrays.asList("settlement_end_date"));
        customHead.add(Arrays.asList("deposit_date"));
        customHead.add(Arrays.asList("total_amount"));
        customHead.add(Arrays.asList("currency"));
        customHead.add(Arrays.asList("transaction_type"));
        customHead.add(Arrays.asList("order_id"));
        customHead.add(Arrays.asList("merchant_order_id"));
        customHead.add(Arrays.asList("adjustment_id"));
        customHead.add(Arrays.asList("shipment_id"));
        customHead.add(Arrays.asList("marketplace_name"));
        customHead.add(Arrays.asList("amount_type"));
        customHead.add(Arrays.asList("amount_description"));
        customHead.add(Arrays.asList("amount"));
        customHead.add(Arrays.asList("fulfillment_id"));
        customHead.add(Arrays.asList("posted_date"));
        customHead.add(Arrays.asList("posted_date_time"));
        customHead.add(Arrays.asList("order_item_code"));
        customHead.add(Arrays.asList("merchant_order_item_id"));
        customHead.add(Arrays.asList("merchant_adjustment_item_id"));
        customHead.add(Arrays.asList("sku"));
        customHead.add(Arrays.asList("quantity_purchased"));
        customHead.add(Arrays.asList("promotion_id"));
        customHead.add(Arrays.asList("fee_name"));
        customHead.add(Arrays.asList("listing_name"));

        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("费用类型匹配表")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToCustomOrder(list)); // 转换数据顺序
    }

    /**
     * 将原始数据转换为与自定义表头匹配的顺序
     */
    private List<List<Object>> convertDataToCustomOrder(List<Vt> dataList) {
        List<List<Object>> result = new ArrayList<>();
        for (Vt vt : dataList) {
            List<Object> row = new ArrayList<>();
            row.add(vt.getId());
            row.add(vt.getPeriod());
            row.add(vt.getShop_name());
            row.add(vt.getBrand_name());
            row.add(vt.getCountry_name());
            row.add(vt.getFile_name());
            row.add(vt.getSettlement_id());
            row.add(vt.getSettlement_start_date());
            row.add(vt.getSettlement_end_date());
            row.add(vt.getDeposit_date());
            row.add(vt.getTotal_amount());
            row.add(vt.getCurrency());
            row.add(vt.getTransaction_type());
            row.add(vt.getOrder_id());
            row.add(vt.getMerchant_order_id());
            row.add(vt.getAdjustment_id());
            row.add(vt.getShipment_id());
            row.add(vt.getMarketplace_name());
            row.add(vt.getAmount_type());
            row.add(vt.getAmount_description());
            row.add(vt.getAmount());
            row.add(vt.getFulfillment_id());
            row.add(vt.getPosted_date());
            row.add(vt.getPosted_date_time());
            row.add(vt.getOrder_item_code());
            row.add(vt.getMerchant_order_item_id());
            row.add(vt.getMerchant_adjustment_item_id());
            row.add(vt.getSku());
            row.add(vt.getQuantity_purchased());
            row.add(vt.getPromotion_id());
            row.add(vt.getFee_name());
            row.add(vt.getListing_name());
            result.add(row);
        }
        return result;
    }


}
